/* eslint-disable no-unused-vars */
export function filterTree<T extends {
  children?: T[];
}>(
  nodes: T[],
  condition: (node: T) => boolean,
):T[] {
  return nodes
    .filter((node) => {
      if (condition(node)) {
        return false;
      }
      if (node.children) {
      // eslint-disable-next-line no-param-reassign
        node.children = filterTree(node.children, condition);
        return node.children.length > 0;
      }
      return true;
    });
}

export function getFirstLeafNode<T extends { children?: T[] }>(nodes: T[]): T | null {
  let result: T | null = null;
  nodes.forEach((node) => {
    if (!node.children || node.children.length === 0) {
      result = node;
    } else {
      const leafNode = getFirstLeafNode(node.children);
      if (leafNode) {
        result = leafNode;
      }
    }
  });
  return result;
}
export function findNode<T extends { children?: T[] }>(
  nodes: T[],
  condition: (node: T) => boolean,
): T | null {
  // eslint-disable-next-line no-restricted-syntax
  for (const node of nodes) {
    if (condition(node)) {
      return node;
    }
    if (node.children) {
      const foundNode = findNode(node.children, condition);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
}
